package cn.liangcaomei.eduservice.controller;


import cn.liangcaomei.commonutils.R;
import cn.liangcaomei.eduservice.client.VodClient;
import cn.liangcaomei.eduservice.entity.EduVideo;
import cn.liangcaomei.eduservice.service.EduVideoService;
import cn.liangcaomei.servicebase.exceptionhandler.CustException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author LiuJie
 * @since 2024-01-27
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {
    @Autowired
    private EduVideoService eduVideoService;

    //注入 VodClient
    @Autowired
    private VodClient vodClient;

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    //根据id查询小节
    @GetMapping("getVideoById/{id}")
    public R getVideoById(@PathVariable String id) {
        EduVideo videoById = eduVideoService.getById(id);
        return R.ok().data("video", videoById);
    }

    //修改小节
    @PostMapping("udpateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

    //删除小节时，需同时删除视频
    @DeleteMapping("{videoId}")
    public R deleteVideo(@PathVariable String videoId) {
        //根据小节id，得到视频id
        EduVideo byId = eduVideoService.getById(videoId);
        String videoSourceId = byId.getVideoSourceId();

        if (!StringUtils.isEmpty(videoSourceId)) {
            //根据视频id，通过远程调用实现删除视频
            R result = vodClient.removeALiyVideo(videoSourceId);
            if (result.getCode() == 20001) {
                throw new CustException(20001,"删除视频出错了,熔断器。。。");
            }
        }

        eduVideoService.removeById(videoId);
        return R.ok();
    }

}

